package db

import (
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

//GetOne Get 查询单条数据
func GetOne(query *gorm.DB, out interface{}) (bool, error) {
	result := query.First(out)
	if err := result.Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil
		}
		return false, errors.Wrap(err, "get one")
	}
	return true, nil
}

// Exist 检查数据是否存在
func Exist(model interface{}, query *gorm.DB) (bool, error) {
	var count int64
	result := query.Model(model).Count(&count)
	if err := result.Error; err != nil {
		return false, errors.Wrap(err, "check count")
	}
	return count > 0, nil
}

// FindPage 查询分页数据并返回 total [D]
func FindPage(queryScope *gorm.DB, page, size int, out interface{}) (int, error) {
	var count int64
	result := queryScope.Count(&count)
	if err := result.Error; err != nil {
		return 0, errors.Wrap(err, "find count")
	} else if count == 0 {
		return 0, nil
	}

	// 如果分页大小小于0，则不查询数据
	if page < 0 || size < 0 {
		return int(count), nil
	}

	if page > 0 && size > 0 {
		queryScope = queryScope.Offset((page - 1) * size)
	}
	if size > 0 {
		queryScope = queryScope.Limit(size)
	}
	if err := queryScope.Find(out).Error; err != nil {
		return 0, errors.Wrap(err, "find page")
	}

	return int(count), nil
}

// FindPageNoTotal 查询分页数据并返回 total [D]
func FindPageNoTotal(queryScope *gorm.DB, page, size int, out interface{}) error {
	// 如果分页大小小于0，则不查询数据
	if page < 0 || size < 0 {
		return nil
	}

	if page > 0 && size > 0 {
		queryScope = queryScope.Offset((page - 1) * size)
	}
	if size > 0 {
		queryScope = queryScope.Limit(size)
	}
	if err := queryScope.Find(out).Error; err != nil {
		return errors.Wrap(err, "find page")
	}

	return nil
}
